﻿using FluentFTP;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZhonTai.Admin.Core.Attributes;

namespace ZhonTai.Industry.Core.Tool
{
    /// <summary>
    /// FTP文件下载远端删除
    /// </summary>
    [InjectTransient]
    public class FtpExample
    {
        private string _ftpHost;
        private string _ftpUser;
        private string _ftpPass;
        private string _remoteFolderPath;

        public FtpExample(string ftpHost, string ftpUser, string ftpPass, string remoteFolderPath)
        {
            _ftpHost = ftpHost;
            _ftpUser = ftpUser;
            _ftpPass = ftpPass;
            _remoteFolderPath = remoteFolderPath.TrimEnd('/'); // 确保路径不以斜杠结尾
        }

        public void DownloadLatestFile(string localFileName)
        {
            using (var client = new FtpClient(_ftpHost, _ftpUser, _ftpPass))
            {
                client.Encoding = System.Text.Encoding.UTF8; // 设置编码，如果需要的话
                client.Connect();
                try
                {
                    {
                        var fileToDownload = client.GetListing(_remoteFolderPath + "/", FtpListOption.AllFiles)
                                                   .Where(f => f.Type == FtpObjectType.File && f.Name.EndsWith(".xlsx"))
                                                   .OrderByDescending(o => o.Modified)
                                                   .FirstOrDefault();
                        var remoteFilePath = fileToDownload?.FullName;
                        var localSavePath = Path.GetDirectoryName(localFileName) ?? ".";
                        var localFilePath = Path.Combine(localSavePath, Path.GetFileName(localFileName));
                        var re = Directory.CreateDirectory(localSavePath);
                        if (re.Exists)
                        {
                            client.DownloadFile(localFilePath, remoteFilePath, FtpLocalExists.Overwrite);
                            client.DeleteFile(remoteFilePath);
                        }
                    }
                }
                catch
                {
                }
                finally
                {
                    client.Disconnect();
                }
            }
        }
    }
}